package com.sita.bluetactivity.SafeFragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;

import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;

import com.amap.api.maps.model.MyLocationStyle;
import com.google.gson.Gson;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BaseValue;
import com.sita.bluetactivity.Base.SpUtils;
import com.sita.bluetactivity.Base.ToastUtils;
import com.sita.bluetactivity.R;
import com.sita.bluetactivity.TripFragment.GpsCorrect;
import com.sita.bluetactivity.VehicleFragment.BoDaoLocation;
import com.sita.bluetactivity.VehicleFragment.VehicleToken;
import com.sita.bluetactivity.http.RestClient;

import java.text.SimpleDateFormat;
import java.util.Map;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.BLUETOOTH;
import static android.Manifest.permission.BLUETOOTH_ADMIN;


/**
 * Created by Jason on 2016/9/21.
 */
public class VehicleSafeFragment extends Fragment implements View.OnClickListener,AMap.OnMapLongClickListener
    ,LocationSource,AMapLocationListener
{
    private TextureMapView safeMap;
    final int REQ_LOCATION = 0x12;
    private AMap aMap;
    private UiSettings uiSetting;
    private LatLng bodaolatLng;//定位坐标
    private Gson gson = new Gson();
    private VehicleToken token = new VehicleToken();
    private BoDaoLocation boDaoLocation= new BoDaoLocation();
    private Marker vehicleLocationMarker;
    private ImageView bodaoLocaion;
    private static Handler handler = new Handler();
    private EditText radiusEdT;
    private Switch setSwitch;
    /****地图*****/
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private OnLocationChangedListener mListener;
    /****地图*****/
    private LatLng nowLocation ;
    private Button setBtn;
    private LatLng latLngBJ = new LatLng(39.149124,117.276275);//起始位置
    private FancesBackBean backBean;
    private static int fancesID;
    private SimpleDateFormat sDateFormat;
    private String nowData;
    private String boDaoId;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.e("VehicleLocation","定位车辆位置");
            handler.postDelayed(runnable,5000);
        }
    };
    private void startTime(){
        handler.post(runnable);
    }
    private void stopTime(){
        handler.removeCallbacks(runnable);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_safevehicle,null);
        startTime();
        safeMap = (TextureMapView) view.findViewById(R.id.safe_map);
        safeMap.onCreate(savedInstanceState);
        return view;
    }
    /*********************************************************************/
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        nowData = getTime();
        boDaoId = SpUtils.getString("BoDaoID",null,BaseApplication.getContext());
        initView();
        initMap();
        intMapUi();
        getFances();
        applyPermission();

    }

    private void initView(){

        bodaoLocaion = (ImageView) getActivity().findViewById(R.id.vehicle_bodao_location);
        bodaoLocaion.setOnClickListener(this);
        setBtn = (Button) getActivity().findViewById(R.id.setFen_Bt);
        setBtn.setOnClickListener(this);
        radiusEdT = (EditText) getActivity().findViewById(R.id.weilan);
        setSwitch = (Switch) getActivity().findViewById(R.id.setfencing);
        //记录switch的关闭状态
        radiusEdT.setText(SpUtils.getString("Radius","500",BaseApplication.getContext()));
        setSwitch.setChecked(SpUtils.getBoolean("Warning",false,BaseApplication.getContext()));

        setSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    BaseValue.Warning = true;

                    }
                else {
                    BaseValue.Warning = false;

                }
            }
        });

    }

    private void initMap(){
        aMap = safeMap.getMap();
        aMap.setLocationSource(this);
        aMap.setOnMapLongClickListener(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getActivity());
        }
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.person_icon));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色  
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色  
        aMap.setMyLocationStyle(myLocationStyle);

    }





    @Override
    public void onResume() {
        super.onResume();
        safeMap.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
      safeMap.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        safeMap.onDestroy();



    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        safeMap.onSaveInstanceState(outState);
    }
    private void intMapUi(){

        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        aMap.setMyLocationEnabled(true);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        uiSetting =   aMap.getUiSettings();
        uiSetting.setZoomControlsEnabled(false);
    }
    /*********************************************************************/
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            stopTime();
            deactivate();
            SpUtils.putBoolean("Warning",BaseValue.Warning,BaseApplication.getContext());//记录switch的关闭状态

        }
        else {
            startTime();
            getFances();
            boDaoId = SpUtils.getString("BoDaoID",null,BaseApplication.getContext());
            nowData = getTime();


        }
    }
    //获取时间
    private  String getTime(){
        sDateFormat    =   new    SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        return sDateFormat.format(new    java.util.Date());
    }
//移动坐标到这个坐标
    private void   showVehicleLocation(LatLng latLng ){
        if (latLng!=null){
            aMap.moveCamera(CameraUpdateFactory.
                    newCameraPosition(new CameraPosition(latLng,15,0,0)));
        }
    }

    private void showVehicle(LatLng latlng,double radio){
        aMap.clear();
        if (latlng!=null){
            showVehicleLocation(latlng);//移动
        }
            Bitmap locationMe = BitmapFactory.decodeResource(
                    this.getResources(), R.mipmap.vehicle_location);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            vehicleLocationMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latlng).setFlat(true));


            vehicleLocationMarker.setPosition(latlng);

        if (String.valueOf(radio).length()>=0){
            //mLocationClient.addGeoFenceAlert("fenceId", latlng.latitude, latlng.longitude, 100, -1, null);
            addCircle(latlng,radio);
        }
    }
    private void showDriverLocation(LatLng latlng){
        if (latlng!=null){
            Bitmap locationMe = BitmapFactory.decodeResource(
                    this.getResources(), R.mipmap.person_icon);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            vehicleLocationMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latlng).setFlat(true));


            vehicleLocationMarker.setPosition(latlng);
        }



    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.vehicle_bodao_location:
                if (bodaolatLng!=null){
                    showVehicleLocation(bodaolatLng);
                }
                break;
            case R.id.setFen_Bt:
                //设置围栏

                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.create();
                builder.setMessage("确定要设置围栏?");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        builder.create().dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        builder.create().dismiss();
                        setFances();
                    }
                });
                builder.show();
                break;
        }
    }
    /*********************************************************************/
    private void setFances(){
        if (setSwitch.isChecked()){
            if (radiusEdT.getText().length()==0||Integer.valueOf(radiusEdT.getText().toString())<200||Integer.valueOf(radiusEdT.getText().toString())>20000){
                ToastUtils.show("请输入小于20公里大于200米的围栏范围!",1000);
            }
                else if (Integer.valueOf(radiusEdT.getText().toString())>=200&&Integer.valueOf(radiusEdT.getText().toString())<200000){
                setFancesFromBoDao();
            }
        }
        else {
            ToastUtils.show("请打开报警设置",1000);
        }
    }
    /******************************post  设置围栏***************************************/
    private void setFancesFromBoDao(){
        HttpParams params = new HttpParams();
        params.put("id",0);
        params.putHeaders("Authorization","bearer"+" "+SpUtils.getString("Token",null,BaseApplication.getContext()));
        params.put("user_id",boDaoId);
        if (BaseValue.Warning){
            params.put("validate_flag",1);
        }else {
            params.put("validate_flag",0);
        }
        params.put("lat",String.valueOf(nowLocation.latitude));
        params.put("lng",String.valueOf(nowLocation.longitude));
        params.put("radius",radiusEdT.getText().toString());
        params.put("create_time",nowData);
        RxVolley.post("http://api.gpslink.cn/api/Fances", params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                Log.e("1000000","首次设置成功");
                ToastUtils.show("围栏设置成功",300);
                SpUtils.putString("Radius",radiusEdT.getText().toString(),BaseApplication.getContext());
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                Log.e("1000000",errorNo+"ssss"+"修改围栏的设置");
                switch (errorNo){
                    case 400:
                        //进修围栏的参数
                        UpFancesData(fancesID);
                        break;
                    case 404:
                    case 401:
                    case 500:
                        ToastUtils.show("围栏设置失败",3000);
                        break;

                }

                //设置失败
            }
        });

    }


    /****************************** put 更新围栏***************************************/
    //更新围栏的数据   fancesID = backBean.getId();
    private void UpFancesData(int fancesID){

        String url = "http://api.gpslink.cn/api/Fances/"+fancesID;
        Log.e("1000000",url);
        PutFancesRequest request = new PutFancesRequest();
        request.id=fancesID;
        request.create_time =nowData;
        request.radius =Integer.valueOf(radiusEdT.getText().toString());
        request.lat = String.valueOf(nowLocation.latitude);
        request.lng = String.valueOf(nowLocation.longitude);
        Log.e("1000000","new坐标"+nowLocation.latitude+" vvvv"+nowLocation.longitude);

        if (BaseValue.Warning){
            request.validate_flag = 1;
        }else {
            request.validate_flag = 0;
        }

        request.user_id = boDaoId;
        HttpParams params = new HttpParams();
        String jsonParam = JSONObject.toJSONString(request);
        Log.e("1000000",jsonParam);
        params.putHeaders("Authorization","bearer"+" "+SpUtils.getString("Token",token.getAccess_token(),BaseApplication.getContext()));
        params.putJsonParams(jsonParam);
        HttpCallback httpCallback = new HttpCallback() {
            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                Log.e("1000000",errorNo+"更新失败"+strMsg);
                Log.e("1000000",SpUtils.getString("Token",token.getAccess_token(),BaseApplication.getContext())  );
            }

            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                Log.e("1000000","更新成功");
                ToastUtils.show("围栏更新成功",3000);

                SpUtils.putString("Radius",radiusEdT.getText().toString(),BaseApplication.getContext());

            }

            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);
            }
        };

         new RxVolley.Builder().httpMethod(RxVolley.Method.PUT)
                 .url(url)
                 .contentType(RxVolley.ContentType.JSON)
                 .params(params)
                 .shouldCache(false)
                 .callback(httpCallback)
                 .encoding("UTF-8")
                 .doTask();


    }
    //画一个圆
    public void addCircle(LatLng latLng,double radius){
        CircleOptions circleOptions=new CircleOptions();
        circleOptions.center(latLng);
        circleOptions.radius(radius);
        circleOptions.strokeWidth(4);
        circleOptions.strokeColor(ContextCompat.getColor(BaseApplication.getContext(),R.color.circle));
        circleOptions.fillColor(ContextCompat.getColor(BaseApplication.getContext(),R.color.Circle_line));
        aMap.addCircle(circleOptions);
    }
    @Override
    public void onMapLongClick(LatLng latLng) {
        nowLocation = latLng;
        Log.e("10000",nowLocation.latitude+"sss"+nowLocation.longitude);
        aMap.clear();
        showVehicle(latLng,100);
    }

//获取设备的围栏状况  get请求
   private void getFances(){
       HttpParams params  =new HttpParams();
       if (boDaoId!=null){
           params.put("cid",boDaoId);
       }
       params.put("type",1);
       params.putHeaders("Authorization","bearer"+" "+SpUtils.getString("Token",token.getAccess_token(),BaseApplication.getContext()));
       Log.e("0000000","bearer"+" "+SpUtils.getString("Token",token.getAccess_token(),BaseApplication.getContext()));
       HttpCallback httpCallback  = new HttpCallback() {
           @Override
           public void onSuccess(String t) {
               super.onSuccess(t);
               //找到了的围栏设置
               if (t!=null) {
                   backBean = new FancesBackBean();
                   backBean = gson.fromJson(t, FancesBackBean.class);
                   fancesID = backBean.getId();
                   Log.e("1000000", fancesID + "" + "dfdd");
                   Log.e("1000000", t);
                   LatLng newLatLng = new LatLng(Double.valueOf(backBean.getLat()), Double.valueOf(backBean.getLng()));
                   bodaolatLng = newLatLng;//车的位置
                   nowLocation = newLatLng;//如果没有更新新的围栏中心则调用get到的位置作为位置中心
                   showVehicle(newLatLng, backBean.getRadius());
               }
           }

           @Override
           public void onFailure(int errorNo, String strMsg) {
               super.onFailure(errorNo, strMsg);
              // 获取围栏失败以后设置到ttianj
               showVehicle(latLngBJ,100);
               showVehicleLocation(latLngBJ);
               Log.e("1000000",errorNo+"");
           }
       };
       new RxVolley.Builder().httpMethod(RxVolley.Method.GET)
               .url("http://api.gpslink.cn/api/Fances")
               .contentType(RxVolley.ContentType.JSON)
               .params(params)
               .shouldCache(false)//
               .callback(httpCallback)
               .encoding("UTF-8")
               .cacheTime(0)
               .doTask();
   }
/**************************定位回调****************************/
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener!=null){
            //mListener.onLocationChanged(aMapLocation);
            LatLng driverLocation = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            showDriverLocation(driverLocation);
        }

    }

    @Override
    public void onStart() {
        super.onStart();

    }

    /*****************************开启定位*************************/
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
       mLocationOption = new AMapLocationClientOption();
        //设置监听
        mLocationClient.setLocationListener(this);
        mLocationOption.setInterval(3000);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }
    /*****************************结束定位*************************/
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;

    }
    public void applyPermission() {
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION},
                REQ_LOCATION);
    }
}
